import io
import time

import requests

import cfg
from database_handler import DatabaseHandler
from logger import log

src_cs = f'mysql+pymysql://{cfg.src_user}:{cfg.src_password}@{cfg.src_host}:{cfg.src_port}/platform_prod_zhongke'
src_db = DatabaseHandler(src_cs)

tar_cs = f'mysql+pymysql://{cfg.tar_user}:{cfg.tar_password}@{cfg.tar_host}:{cfg.tar_port}/platform_prod_zhongke'
tar_db = DatabaseHandler(tar_cs)

upload_url = "http://192.168.241.136/upload/upload"

while True:
    try:
        where_params = {
            'block_id_dict_text': "中慧1号储煤棚",
            'create_time__gt': f"{cfg.get_latest_time('block_scan')}"
        }
        items = src_db.query('block_scan', where_params=where_params, order_by=['create_time ASC'])
        log.info(f"获取到数据items:{len(items)}")
        for item in items:
            query = tar_db.query('block_scan', columns=['id'], where_params={'id': item['id']})
            if len(query) > 0:
                log.info(f"数据已存在:{query}")
                continue
            log.info(f"开始处理数据:{item['id']}")
            # https://api-4d.sinok.com.cn/file/block/1928260765772382210/1930074615073177601/engineering_calculation/1749004787845571_out_grid.ply
            ply_url = item.get("ply")
            split = ply_url.split('/')
            filename = split[len(split) - 1]
            # 在内存中下载文件
            try:
                log.info(f"开始下载: {ply_url}")
                response = requests.get(ply_url, stream=True)
                response.raise_for_status()
                # 将文件内容读入内存
                file_data = io.BytesIO(response.content)

                log.info(f"开始上传: {filename}")
                # 注意：requests 上传时需要提供文件名和内容类型
                files = {'file': (filename, file_data.getvalue(), 'application/octet-stream')}
                response = requests.post(upload_url, files=files)
                response.raise_for_status()
                result = response.json()
                log.info(f"上传成功: {result}")
                item["ply"] = f'/file/{filename}'  # 替换为新的路径格式
                tar_db.insert('block_scan', item)
            except Exception as e:
                log.error(f"下载文件失败: {e}")

        if len(items) > 0:
            time_ = items[len(items) - 1]['create_time']
            cfg.set_latest_time('block_scan', time_.strftime('%Y-%m-%d %H:%M:%S'))
            log.info(f"更新时间:{cfg.get_latest_time('block_scan')}")
        else:
            log.info(f"没有数据")
    except Exception as e:
        log.error(e)
    time.sleep(60)
